package com.disc.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.disc.baidu.BaiDuLogin;
import com.disc.baidu.BaiduPanService;
import com.disc.baidu.BaiduUser;
import com.disc.common.Constant;
import com.disc.common.DiscResponse;
import com.disc.heike.HeiKeLogin;
import com.disc.open189.Open189PanService;
import com.disc.open189.TianYiLogin;
import com.disc.service.DiscService;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Tonight on 2017/7/18.
 */
@Service
public class DiscServiceImpl implements DiscService{

    @Override
    public DiscResponse loginBaidu(BaiduUser baiduUser, HttpSession session) {
        DiscResponse discResponse;
        try
        {
            BaiDuLogin baiDuLogin  = (BaiDuLogin)session.getAttribute(baiduUser.getAccount());
            if(baiDuLogin == null)
            {
                baiDuLogin = new BaiDuLogin();
                session.setAttribute(baiduUser.getAccount(),baiDuLogin);
                //初始化cookie
                baiDuLogin.initCookie();
            }
            //获取token
            String token = baiDuLogin.getToken();
            //获取加密key
            Map<String,String> publicKeyMap =  baiDuLogin.getPublicKey(token);

            discResponse = baiDuLogin.login(publicKeyMap,token,baiduUser);

            if("0".equals(discResponse.getCode()))
            {
                baiDuLogin.createTime = new Date();
                Constant.cookieStoreMap.put(baiduUser.getAccount(),baiDuLogin);
                session.removeAttribute(baiduUser.getAccount());
            }
            else
            {
                session.setAttribute(baiduUser.getAccount(),baiDuLogin);
            }
        }
        catch (Exception e)
        {
            discResponse = new DiscResponse();
            discResponse.setCode("-999");
            discResponse.setMessage("系统异常！");
        }
        return discResponse;
    }


    @Override
    public DiscResponse loginTianYi(BaiduUser baiduUser, HttpSession session) {
        DiscResponse discResponse;
        try
        {
            TianYiLogin tianYiLogin  = (TianYiLogin)session.getAttribute(baiduUser.getAccount());
            if(tianYiLogin == null)
            {
                tianYiLogin = new TianYiLogin();
                session.setAttribute(baiduUser.getAccount(),tianYiLogin);
                //初始化cookie
                tianYiLogin.initCookie();
            }
            //获取token
            Map<String,String> resultMap = tianYiLogin.getCaptchaToken();

            discResponse = tianYiLogin.login(resultMap,baiduUser);

            if("0".equals(discResponse.getCode()))
            {
                tianYiLogin.createTime = new Date();
                Constant.cookieStoreMap.put(baiduUser.getAccount(),tianYiLogin);
                session.removeAttribute(baiduUser.getAccount());
            }
            else
            {
                session.setAttribute(baiduUser.getAccount(),tianYiLogin);
            }
        }
        catch (Exception e)
        {
            discResponse = new DiscResponse();
            discResponse.setCode("-999");
            discResponse.setMessage("系统异常！");
        }
        return discResponse;
    }

    @Override
    public DiscResponse getFileList(String dir, String account)
    {
        try
        {
            BaiDuLogin baiDuLogin  = (BaiDuLogin)Constant.cookieStoreMap.get(account);
            BaiduPanService baiduPanService = new BaiduPanService();
            baiduPanService.baiDuLogin = baiDuLogin;
        }
        catch (Exception e)
        {

        }
        return null;
    }

    @Override
    public DiscResponse getTianYiFileDownloadUrl(String fileUrl, String account) {
        DiscResponse discResponse = new DiscResponse();
        try
        {
            TianYiLogin tianYiLogin  = (TianYiLogin)Constant.cookieStoreMap.get(account);
            Open189PanService open189PanService = new Open189PanService();
            open189PanService.tianYiLogin = tianYiLogin;
            String result = open189PanService.getFileDownloadUrl(fileUrl);
            discResponse.setCode("0");
            discResponse.setMessage("获取成功！");
            discResponse.setResult(result);
        }
        catch (Exception e)
        {
            discResponse.setCode("-1");
            discResponse.setMessage("获取异常！");
            e.printStackTrace();
        }
        return discResponse;
    }


    @Override
    public DiscResponse getFileDownloadUrl(String fileUrl, String account)
    {
        try
        {
            BaiDuLogin baiDuLogin  =  (BaiDuLogin)Constant.cookieStoreMap.get(account);
            BaiduPanService baiduPanService = new BaiduPanService();
            baiduPanService.baiDuLogin = baiDuLogin;
            String a = baiduPanService.getFileDownloadUrl(fileUrl);
            System.out.print(a);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public DiscResponse getSingleTianYiFileDownloadUrl(String fileid, String account)
    {
        DiscResponse discResponse = new DiscResponse();
        discResponse.setCode("-1");
        discResponse.setMessage("获取失败！");
        Map<String,JSONObject> panFile = Constant.fileStoreMap.get(account);
        if(panFile == null)
        {
            panFile = new HashMap<>();
            Constant.fileStoreMap.put(account,panFile);
        }
        JSONObject json = panFile.get(fileid);
        if(json == null || ((new Date().getTime() - json.getLong("getTime")) > 3600000))
        {
            String parentId = fileid.split(",")[0];
            DiscResponse itemDiscResponse = getTianYiFileDownloadUrl(parentId,account);
            if("0".equals(itemDiscResponse.getCode()))
            {
               JSONObject resultJson = JSONObject.parseObject(itemDiscResponse.getResult().toString());
               JSONArray fileArray =  resultJson.getJSONArray("data");
                for (int index=0;index < fileArray.size();index++)
                {
                    JSONObject item = fileArray.getJSONObject(index);
                    if(item.getString("fileType") != null && !"".equals(item.getString("fileType")))
                    {
                        item.put("getTime",new Date().getTime());
                        if(item.getString("videoUrl") != null && !"".equals(item.getString("videoUrl")))
                        {
                            TianYiLogin tianYiLogin  = (TianYiLogin)Constant.cookieStoreMap.get(account);
                            Open189PanService open189PanService = new Open189PanService();
                            open189PanService.tianYiLogin = tianYiLogin;
                            try {
                                String  result = open189PanService.getVideoDownloadUrl(item.getString("videoUrl"));
                                if(result != null && !"".equals(result))
                                {
                                    String realVideoUrl = JSONObject.parseObject(result).getString("url");
                                    if(realVideoUrl != null && !"".equals(realVideoUrl))
                                    {
                                        item.put("realVideoUrl",realVideoUrl);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        String itemFileId = (item.getString("parentId") + "," + item.getString("fileId"));
                        if(itemFileId.equals(fileid))
                        {
                            json = item;
                            discResponse.setResult(json);
                            discResponse.setCode("0");
                            discResponse.setMessage("获取成功！");
                        }
                        panFile.put(itemFileId,item);
                    }
                }

            }
        }
        else
        {
            discResponse.setResult(json);
            discResponse.setCode("0");
            discResponse.setMessage("获取成功！");
        }
        return discResponse;
    }

    @Override
    public DiscResponse loginHeiKe(BaiduUser baiduUser, HttpSession session) {
        DiscResponse  discResponse = null;
        try
        {
            HeiKeLogin heiKeLogin = (HeiKeLogin)session.getAttribute(Constant.HEIKE_HTTPCLIENT_TAG);
            Map<String,String> resultMap = (Map<String,String>)session.getAttribute(Constant.HEIKE_HTTPCLIENT_LOGIN_VALUE);
            discResponse = heiKeLogin.login(baiduUser,resultMap);
            if("0".equals(discResponse.getCode()))
            {
                Constant.cookieStoreMap.put(baiduUser.getAccount(),heiKeLogin);
                session.removeAttribute(Constant.HEIKE_HTTPCLIENT_TAG);
                session.removeAttribute(Constant.HEIKE_HTTPCLIENT_LOGIN_VALUE);
            }

        }catch (Exception e)
        {

        }

        return discResponse;
    }



    @Override
    public byte[] getVcodeImageStream(HttpSession session){
        HeiKeLogin heiKeLogin = (HeiKeLogin)session.getAttribute(Constant.HEIKE_HTTPCLIENT_TAG);
        return heiKeLogin.getVcodeImage();
    }

    @Override
    public DiscResponse initHeiKeCookie(HttpSession session) {
        DiscResponse discResponse = new DiscResponse();
        try
        {
            HeiKeLogin heiKeLogin = (HeiKeLogin)session.getAttribute(Constant.HEIKE_HTTPCLIENT_TAG);
            if(heiKeLogin == null)
            {
                heiKeLogin = new HeiKeLogin();
                session.setAttribute(Constant.HEIKE_HTTPCLIENT_TAG,heiKeLogin);
            }
         Map<String,String> resultValue = heiKeLogin.initCookie();
         session.setAttribute(Constant.HEIKE_HTTPCLIENT_LOGIN_VALUE,resultValue);
         discResponse.setCode("0");
         discResponse.setMessage("初始化成功！");
        }
        catch (Exception e)
        {
            discResponse.setCode("-1");
            discResponse.setMessage("初始化失败！");
        }
        return discResponse;
    }
}
